package com.niuwa.p2p.service.impl.borrowinfomg;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.core.utils.DictConstant.BORROWER_TYPE;
import com.niuwa.p2p.core.utils.DictConstant.BorrowOperAuditType;
import com.niuwa.p2p.core.utils.DictConstant.LoanAuditStatus;
import com.niuwa.p2p.core.utils.StringUtil;
import com.niuwa.p2p.dao.borrowinfomg.IBorrowInfoDao;
import com.niuwa.p2p.dao.business.LoanClaimDao;
import com.niuwa.p2p.dao.channel.ChannelInfoDao;
import com.niuwa.p2p.dao.channel.CorporationDao;
import com.niuwa.p2p.dao.channel.LoanClaimAuditDao;
import com.niuwa.p2p.dao.channel.LoanClaimDetailDao;
import com.niuwa.p2p.dao.channel.LoanClaimImgDao;
import com.niuwa.p2p.dao.channel.LoanFinanceDao;
import com.niuwa.p2p.entity.PageQuery;
import com.niuwa.p2p.entity.channel.ChannelInfo;
import com.niuwa.p2p.entity.channel.Corporation;
import com.niuwa.p2p.entity.channel.LoanClaimAudit;
import com.niuwa.p2p.entity.channel.LoanClaimImg;
import com.niuwa.p2p.entity.channel.LoanFinance;
import com.niuwa.p2p.exception.BusinessException;
import com.niuwa.p2p.service.borrowinfomg.IBorrowInfoService;
import com.niuwa.p2p.vo.borrowinfomg.LoanInfoVo;
import com.niuwa.p2p.vo.borrowinfomg.enterpriseinfomg.AppBorrowInfoVo;
import com.niuwa.p2p.vo.borrowinfomg.enterpriseinfomg.P2PBorrowInfoVo;

@Service
class BorrowInfoService implements IBorrowInfoService {

	@Autowired
	private IBorrowInfoDao borrowInfoDao;
	@Autowired
	private LoanClaimDao loanClaimDao;
	@Autowired
	private LoanClaimDetailDao loanClaimDetailDao;
	@Autowired
	private LoanClaimImgDao loanClaimImgDao;
	@Autowired
	private LoanFinanceDao loanFinanceDao;
	@Autowired
	private LoanClaimAuditDao loanClaimAuditDao;
	@Autowired
	private ChannelInfoDao channelInfoDao;
	@Autowired
	private CorporationDao corporationDao;

	/**
	 * 查询p2p借款项目信息列表
	 * 
	 * @param paramMap
	 * @return
	 */
	@Override
	public PageBean<P2PBorrowInfoVo> searchP2PBorrowinfo(Map<String, Object> paramMap) {
		int totalCount = borrowInfoDao.count(BORROWER_TYPE.CORPORATION.getCode());
		PageBean<P2PBorrowInfoVo> page = new PageBean<P2PBorrowInfoVo>(totalCount);
		// 设置当前页
		page.setPage(((PageQuery) paramMap.get(PageQuery.PAGEQUERY)).getPage());
		List<P2PBorrowInfoVo> p2pBorrowInfos = new ArrayList<P2PBorrowInfoVo>();
		p2pBorrowInfos = borrowInfoDao.searchP2PBorrowinfo(paramMap);
		for (P2PBorrowInfoVo p2pBorrowInfoVo : p2pBorrowInfos) {
			p2pBorrowInfoVo.setInvestAmount(borrowInfoDao.searchInvetAmount(p2pBorrowInfoVo.getProjectNo()));
		}
		page.setRows(borrowInfoDao.searchP2PBorrowinfo(paramMap));
		return page;
	}

	@Override
	public boolean addLoanInfo(LoanInfoVo loanInfo) throws BusinessException {
		String seqValue = this.getNextLoanSeq();
		// TODO 这里需要判断借款人类型，目前只有企业
		String projectNo = "JKC" + seqValue;
		loanInfo.getLoanClaim().setProjectNo(projectNo);
		loanInfo.getLoanClaim().setBorrowerType("CORPORATION");
		loanInfo.getLoanClaim().setCreateTime(new Date());
		loanInfo.getLoanClaim().setAuditStatus("EDIT");
		loanInfo.getLoanClaimDetail().setProjectNo(projectNo);
		loanInfo.getLoanClaimDetail().setCreateTime(new Date());
		if(null!=loanInfo.getLoanClaimImages()){
			for (LoanClaimImg image : loanInfo.getLoanClaimImages()) {
				if (null == image || StringUtil.isEmpty(image.getFileId())) {
					continue;
				}
				image.setProjectNo(projectNo);
				image.setCreateTime(new Date());
				loanClaimImgDao.insertSelective(image);
			}
		}
		
		for (LoanFinance finance : loanInfo.getLoanFinances()) {
			finance.setProjectNo(projectNo);
			finance.setCreateTime(new Date());
		}
		loanClaimDao.insertLoanClaim(loanInfo.getLoanClaim());
		loanClaimDetailDao.insertSelective(loanInfo.getLoanClaimDetail());
		
		for (LoanFinance finance : loanInfo.getLoanFinances()) {
			loanFinanceDao.insertSelective(finance);
		}
		return true;
	}

	@Override
	public boolean updateLoanInfo(LoanInfoVo loanInfo) throws BusinessException {
		loanClaimDao.updateByPrimaryKeySelective(loanInfo.getLoanClaim());

		loanInfo.getLoanClaimDetail().setProjectNo(loanInfo.getLoanClaim().getProjectNo());
		loanInfo.getLoanClaimDetail().setUpdateTime(new Date());
		loanClaimDetailDao.updateByPrimaryKey(loanInfo.getLoanClaimDetail());

		for (LoanClaimImg image : loanInfo.getLoanClaimImages()) {
			if (null == image) {
				continue;
			}
			image.setProjectNo(loanInfo.getLoanClaim().getProjectNo());
			if (StringUtil.isEmpty(image.getFileId())) {
				loanClaimImgDao.deleteByPrimaryKey(image.getId());
			} else {
				loanClaimImgDao.updateByPrimaryKey(image);
			}
		}
		for (LoanFinance finance : loanInfo.getLoanFinances()) {
			finance.setProjectNo(loanInfo.getLoanClaim().getProjectNo());
			finance.setUpdateTime(new Date());
			loanFinanceDao.updateByPrimaryKey(finance);
		}
		return true;
	}

	@Override
	public synchronized String getNextLoanSeq() {
		// 先查询数据库中的seq
		String value = borrowInfoDao.getNextLoanSeq().toString();
		String year = value.substring(0, 2);
		String month = value.substring(2, 4);
		String seq = value.substring(4);

		// 判断当前时间
		String currentYear = borrowInfoDao.getCurrentYear();
		String currentMonth = borrowInfoDao.getCurrentMonth();

		if ((year + month).equals(currentYear + currentMonth)) {
			seq = String.valueOf(Integer.parseInt(seq) + 1);
			while (seq.length() < 4) {
				seq = "0" + seq;
			}
		} else {
			seq = "0001";
		}

		String newSeq = currentYear + currentMonth + seq;
		// 保存新的编号值
		borrowInfoDao.saveNextLoanSeq(Integer.parseInt(newSeq));
		return newSeq;
	}

	/**
	 * 更新审核状态
	 * 
	 * @param string
	 * @param projectNo
	 */
	@Override
	public boolean updateAuditStatus(LoanAuditStatus auditStatus, String projectNo, Long operator,
			BorrowOperAuditType auditType, String remark) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("auditStatus", auditStatus.getCode());
		paramMap.put("projectNo", projectNo);
		loanClaimDao.updateLoanClaimStatus(paramMap);
		LoanClaimAudit loanClaimAudit = new LoanClaimAudit();
		loanClaimAudit.setCreateTime(new Date());
		loanClaimAudit.setOperateType(auditType.getCode());
		loanClaimAudit.setOperator(operator);
		loanClaimAudit.setProjectNo(projectNo);
		loanClaimAudit.setRemark(remark);
		loanClaimAuditDao.insert(loanClaimAudit);
		return true;
	}

	@Override
	public LoanInfoVo loadLoanInfo(String projectNo) throws BusinessException {
		return borrowInfoDao.loadLoanInfo(projectNo);
	}

	@Override
	public List<LoanClaimAudit> loadLoanAuditLog(String projectNo) {
		return loanClaimAuditDao.selectLoanAuditLog(projectNo);
	}

	/**
	 * 查询App借款项目信息列表
	 * 
	 * @param paramMap
	 * @return
	 */
	@Override
	public PageBean<AppBorrowInfoVo> searchAppBorrowinfo(Map<String, Object> paramMap) {
		int totalCount = borrowInfoDao.count(BORROWER_TYPE.PERSONAL.getCode());
		PageBean<AppBorrowInfoVo> page = new PageBean<AppBorrowInfoVo>(totalCount);

		// 设置当前页
		page.setPage(((PageQuery) paramMap.get(PageQuery.PAGEQUERY)).getPage());

		page.setRows(borrowInfoDao.searchAppBorrowinfo(paramMap));

		return page;
	}

	public BigDecimal loadChannelUsableAmount(String channelCode) {
		ChannelInfo channelInfo = channelInfoDao.selectByPrimaryKey(channelCode);
		return channelInfo.getUsableAmount();
	}

	@Override
	public String loadCorpName(String corpCode) {
		Corporation corporation = corporationDao.selectByPrimaryKey(corpCode);
		return corporation.getCorpName();
	}

}
